package com.mostromas.ess.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mostromas.ess.entities.SysUser;
import com.mostromas.ess.entities.UserProject;
import com.mostromas.ess.feign.IFeignProjectController;
import com.mostromas.ess.system.mapper.SysUserMapper;
import com.mostromas.ess.system.req.RegisterREQ;
import com.mostromas.ess.system.req.SysUserCheckPasswordREQ;
import com.mostromas.ess.system.req.SysUserREQ;
import com.mostromas.ess.system.req.SysUserUpdatePasswordREQ;
import com.mostromas.ess.system.service.ISysUserService;
import com.mostromas.ess.util.base.Result;
import com.mostromas.ess.util.enums.SysUserType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired // 检查启动类注解 @EnableFeignClients
    private IFeignProjectController feignProjectController;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result queryPage(SysUserREQ req) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper();
        // 条件查询
        if(StringUtils.isNotEmpty(req.getUsername())) {
            wrapper.like("username", req.getUsername());
        }
        if(StringUtils.isNotEmpty(req.getMobile())) {
            wrapper.like("mobile", req.getMobile());
        }
        wrapper.orderByDesc("update_date");
        return Result.ok(baseMapper.selectPage(req.getPage(), wrapper));
    }

    @Override
    public Result findRoleIdsById(String id) {
        return Result.ok(baseMapper.findRoleIdsById(id));
    }

    @Transactional //进行事务管理
    @Override
    public Result saveUserRole(String userId, List<String> roleIds) {
        // 1. 先删除用户角色关系表数据
        baseMapper.deleteUserRoleByUserId(userId);
        // 2. 再保存新的用户角色关系数据
        if(CollectionUtils.isNotEmpty(roleIds)) {
            baseMapper.saveUserRole(userId, roleIds);
        }
        return Result.ok();
    }

    @Override
    public Result deleteUserById(String userId) {
        if(StringUtils.isNotEmpty(userId)){
            baseMapper.deleteUserRoleByUserId(userId);
            baseMapper.deleteById(userId);
        }else {
            return Result.error("用户ID不能为空");
        }

        return Result.ok();
    }

    @Override
    public Result checkPassword(SysUserCheckPasswordREQ req) {
        if (StringUtils.isEmpty(req.getUserId())) {
            return Result.error("用户ID不能为空,请重试");
        }
        if(StringUtils.isEmpty(req.getOldPassword())) {
            return Result.error("原密码不能为空,请重试");
        }
        SysUser sysUser = baseMapper.selectById(req.getUserId());
        if(sysUser == null) {
            return Result.error("用户不存在,请重试");
        }
        // 不要少了 !
        if(!passwordEncoder.matches(req.getOldPassword(), sysUser.getPassword())) {
            return Result.error("原密码输入错误");
        }
        return Result.ok();
    }

    @Override
    public Result updatePassword(SysUserUpdatePasswordREQ req) {
        if(StringUtils.isEmpty(req.getUserId())) {
            return Result.error("用户ID不能为空,请重试");
        }
        if(StringUtils.isEmpty(req.getNewPassword())) {
            return Result.error("新密码不能为空,请重试");
        }
        if(StringUtils.isEmpty(req.getRepPassword())) {
            return Result.error("确认密码不能为空,请重试");
        }
        if(!req.getNewPassword().equals(req.getRepPassword())) {
            return Result.error("密码不一致,请重试");
        }
        SysUser sysUser = baseMapper.selectById(req.getUserId());
        if(sysUser == null) {
            return Result.error("用户不存在,请重试");
        }
        // 旧密码
        if(StringUtils.isNotEmpty(req.getOldPassword())) {
            // 不要少了 !
            if(!passwordEncoder.matches(req.getOldPassword(), sysUser.getPassword())) {
                return Result.error("原密码输入错误");
            }
        }
        // 新密码加密
        sysUser.setPassword(passwordEncoder.encode(req.getNewPassword()));
        baseMapper.updateById(sysUser);
        return Result.ok();
    }

    @Override
    public Result resetPassword(RegisterREQ req) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username",req.getUsername());
        SysUser sysUser = baseMapper.selectOne(wrapper);
        if(sysUser == null) {
            return Result.error("用户不存在,请重试");
        }
        sysUser.setPassword(passwordEncoder.encode(req.getPassword()));
        baseMapper.updateById(sysUser);
        return Result.ok();
    }


    @Transactional // 开启事务
    @Override
    public Result update(SysUser sysUser) {
        // 1. 查询原用户信息
        SysUser user = baseMapper.selectById(sysUser.getId());
        if(user == null) {
            return Result.error("更新的用户不存在");
        }

        sysUser.setUpdateDate(new Date());
        baseMapper.updateById(sysUser);
        return Result.ok();
    }

    @Override
    public Result getUserTotal() {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        // 帐户是否可用(1 可用，0 删除用户)
        wrapper.eq("is_enabled", 1);
        Integer total = baseMapper.selectCount(wrapper);
        return Result.ok(total);
    }
    @Override
    public Result checkUsername(String username) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser sysUser = baseMapper.selectOne(wrapper);
        // 查询到则存在，存在 data=true 已被注册，不存在 data=false 未被注册
        return Result.ok( sysUser == null ? false : true );
    }

    @Override
    public SysUser findByUsername(String username) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Transactional //进行事务管理
    @Override
    public Result register(RegisterREQ req) {
        if(StringUtils.isEmpty(req.getUsername())) {
            return Result.error("用户名不能为空，请重试");
        }if(req.getUsername().length() < 5) {
            return Result.error("用户名长度不能小于5");
        }
        if(StringUtils.isEmpty(req.getPassword())) {
            return Result.error("密码不能为空，请重试");
        }
        if(req.getPassword().length() < 6) {
            return Result.error("密码长度不能小于6");
        }
        if(StringUtils.isEmpty(req.getRepPassword())) {
            return Result.error("确认密码不能为空，请重试");
        }
        if( !StringUtils.equals(req.getPassword(), req.getRepPassword())) {
            return Result.error("两次输入的密码不一致");
        }
        Result result = this.checkUsername(req.getUsername());
        if( (Boolean) result.getData() ) {
            return Result.error("用户已被注册，请更换个用户名");
        }
        UserProject info = new UserProject();
        info.setProjectId(req.getProjectId());
        info.setHardwareCoding(req.getHardwareCoding());

        //通过硬件ID和软件ID查询是否有注册过用户
        if(feignProjectController.checkProjectIdHardwareCoding(req.getProjectId(),req.getHardwareCoding()) > 0){
            return Result.error("该机器已经注册过用户，请直接登陆");
        }
        // 校验都通过，新增用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUsername( req.getUsername() );
        // 默认昵称和用户名一样
        sysUser.setNickName( req.getUsername() );

        System.out.println(req.getPassword());
        sysUser.setPassword( passwordEncoder.encode(req.getPassword()) );
        if(StringUtils.isNotEmpty(req.getProjectId())){
            sysUser.setUserType(SysUserType.PROJECT);
        }else {
            sysUser.setUserType(SysUserType.SYSTEM);
        }
        // 提交用户信息
        this.save(sysUser);
        //如果是软件用户
        info.setUsername(sysUser.getUsername());
        info.setDays(3);
        feignProjectController.updateEffectiveTime(info);
        return Result.ok();
    }

    @Override
    public Result selectUsersByDepartmentId(String id) {

        return Result.ok(baseMapper.selectUsersByDepartmentId(id));
    }
}
